package io.github.mengflyl.excel.report.viewer;

import cn.hutool.core.io.FileUtil;
import com.formdev.flatlaf.FlatLaf;
import com.formdev.flatlaf.FlatLightLaf;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.List;

public class MainFrame extends JFrame {


    private final MainWindow mainWindow = new MainWindow();

    public MainFrame() throws HeadlessException {
        super("Excel Report Viewer");

        setContentPane(mainWindow.getContentPanel());

        setSize(new Dimension(800, 600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        getRootPane().setBackground(Color.WHITE);

        initListener();
    }

    private void initListener() {
        getRootPane().setTransferHandler(new TransferHandler() {
            @Override
            public boolean importData(JComponent comp, Transferable t) {
                if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    return false;
                }
                try {
                    @SuppressWarnings("unchecked")
                    java.util.List<File> transferData = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
                    if (transferData.size() == 1) {
                        File file = transferData.get(0);

                        if (FileUtil.getName(file).endsWith(".xml")) {
                            mainWindow.setTemplateFile(file);

                        }
                    }
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
                for (DataFlavor transferFlavor : transferFlavors) {
                    if (DataFlavor.javaFileListFlavor.equals(transferFlavor)) {
                        return true;
                    }
                }
                return false;
            }
        });

        getRootPane().registerKeyboardAction(e -> mainWindow.refresh(false),
                KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
    }


    public static void main(String[] args) {
        initUiSys();
        new MainFrame().setVisible(true);
    }

    public static void initUiSys() {
        try {
            //指定观感，参数为观感类名
            FlatLaf.setup(new FlatLightLaf());
        } catch (Exception ignore) {

        }

        // top menubar background
        UIManager.put("PopupMenu.background", UIManager.getColor("Panel.background"));
        // arrow type
        UIManager.put("Component.arrowType", "chevron");
    }
}
